import java.io.*;
import java.util.Scanner;

public class Demo14 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入要搜索的路径");
        String rootPath = scanner.next();
        File rootFile = new File(rootPath);
        if(!rootFile.isDirectory()){
            System.out.println("输入的路径不是目录");
            return;
        }
        System.out.println("请输入要搜索的关键字");
        String keyword = scanner.next();
        scanDir(rootFile,keyword);
    }

    private static void scanDir(File rootFile, String keyword) {
        File[] files = rootFile.listFiles();
        if(files == null){
            return;
        }
        for (File file : files) {
            if(file.isFile()){
                dealFile(file,keyword);
            }else {
                scanDir(rootFile,keyword);
            }
        }
    }

    private static void dealFile(File file, String keyword) {
        if(file.getName().contains(keyword)){
            System.out.println("文件名包含关键字"+file.getAbsolutePath());
            return;
        }
        StringBuilder stringBuilder = new StringBuilder();
        try(Reader reader = new FileReader(file)) {
            while (true){
                char[] chars = new char[1024];
                int n = reader.read(chars);
                if(n == -1){
                    break;
                }
                stringBuilder.append(chars,0,n);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        if(stringBuilder.indexOf(keyword) >= 0){
            System.out.println("文件内容包含关键字"+file.getAbsolutePath());
        }
        return;
    }
}
